package cn.iune.erp.customer;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Row;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;



@Repository
public class FileCustomerGroupDaoJPAImpl extends BaseJPAImpl<FileCustomerGroup> implements IFileCustomerGroupDao {

	private String kSql;
	
//	@PersistenceContext 
//	private EntityManager em ;


	@Override
	public void insert(FileCustomerGroup obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
//		FileCustomerGroup obj = em.find(FileCustomerGroup.class, fID);
		em.remove(em.getReference(FileCustomerGroup.class, fID));
	}

	@Override
	public FileCustomerGroup update(FileCustomerGroup obj) {
		return em.merge(obj);
	}

	@Override
	public FileCustomerGroup getByID(String fID) {
		FileCustomerGroup singleResult = em.find(FileCustomerGroup.class, fID);
		return singleResult;
	}

	@Override
	public List<FileCustomerGroup> getAll() {
		kSql="SELECT FileCustomerGroup FROM FileCustomerGroup FileCustomerGroup ";
		Query query = em.createQuery(kSql);
		@SuppressWarnings("unchecked")
		List<FileCustomerGroup> resultList = query.getResultList();
		return resultList;
	}
	
	@Override
	public List<FileCustomerGroup> getList(String enterpriseNo, Integer offset, Integer limit) {
		//1、定义sql语句
//		Query query = null;
//		List<Object> params = new ArrayList<Object>();
		Map<String, Object> params = new HashMap<String,Object>();
		
		if(enterpriseNo==null) {
			kSql="SELECT FileCustomerGroup FROM FileCustomerGroup FileCustomerGroup "
					+ " WHERE ( FileCustomerGroup.fParent is null ) "
					+ " ORDER BY FileCustomerGroup.sortNo "
					;

//			query = em.createQuery(kSql);
		}else {
			kSql="SELECT FileCustomerGroup FROM FileCustomerGroup FileCustomerGroup "
					+ " WHERE ( FileCustomerGroup.fParent is null ) "
					+ " AND ( FileCustomerGroup.enterpriseNo = :enterpriseNo ) "
					+ " ORDER BY FileCustomerGroup.sortNo  "
					;

//			query = em.createQuery(kSql);
//			query.setParameter("enterpriseNo", enterpriseNo);
			
//			params.add(enterpriseNo);
			params.put("enterpriseNo", enterpriseNo);
		}
		
		List<FileCustomerGroup> resultList = super.query(kSql, params, offset, limit);
		
		return resultList;
	}
	
	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(FileCustomerGroup.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}


	@Override
	public JSONObject query(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fParent = data.getString("fParent");

		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "FileCustomerGroup.*"
				;
		String from = "FileCustomerGroup FileCustomerGroup"
				;
		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("FileCustomerGroup.groupFullLabel LIKE ? OR FileCustomerGroup.comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fParent
		if (Utils.isNotEmptyString(fParent)) {
			filters.add("fParent='"+fParent+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT ShopCart.fID FROM ShopCart ShopCart    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
//		String idColumn = "fID";
//		table.setIDColumn(idColumn);
//		String parentColumn = "fParent";
//		JSONObject json = Transform.tableToTreeJson(table, parentColumn);
		
		return json;
	}

	@Override
	public JSONObject querySimple(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fParent = data.getString("fParent");

		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "FileCustomerGroup.*"
				;
		String from = "FileCustomerGroup FileCustomerGroup"
				;
		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("FileCustomerGroup.groupFullLabel LIKE ? OR FileCustomerGroup.comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fParent
		if (Utils.isNotEmptyString(fParent)) {
			filters.add("fParent='"+fParent+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT ShopCart.fID FROM ShopCart ShopCart    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		//关闭连接
		conn.close();


		table.setTotal(Integer.parseInt(total.toString()));
		table.setOffset(offset);
		table.setTableName("FileItem");
		
		//JSONObject json = Transform.tableToJson(table);
		
		JSONArray arrayItem = new JSONArray();

		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			FileCustomerGroup obj = JSON.toJavaObject(javaObject, FileCustomerGroup.class);
			
			arrayItem.add(obj);
		}
		
		JSONObject json = new JSONObject();
		
		json.put("data", arrayItem);
		json.put("total", Integer.parseInt(total.toString()));
		json.put("code", 0);
		json.put("msg", "success");
		
//		JSONObject json = Transform.tableToJson(table);
		
		return json;
	}

	

	@Override
	public int getRootCount() {
		// TODO Auto-generated method stub
		kSql="SELECT COUNT(FileCustomerGroup) as count " 
				+ " FROM FileCustomerGroup FileCustomerGroup " 
				+ " WHERE ( FileCustomerGroup.fParent is null ) "
				;
		Query query = em.createQuery(kSql);
		
		long singleResult =  (long) query.getSingleResult();
		return (int) singleResult;
	}

	@Override
	public List<FileCustomerGroup> getRoots(String enterpriseNo) {
		// TODO Auto-generated method stub
		kSql="SELECT FileCustomerGroup FROM FileCustomerGroup FileCustomerGroup "
				+ " WHERE ( FileCustomerGroup.fParent is null ) "
				+ " AND ( FileCustomerGroup.enterpriseNo = :enterpriseNo ) "
				+ " ORDER BY FileCustomerGroup.sortNo ASC "
				;
		
		Query query = em.createQuery(kSql);
		query.setParameter("enterpriseNo", enterpriseNo);
		
		@SuppressWarnings("unchecked")
		List<FileCustomerGroup> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public int getChildCount(String fParent) {
		// TODO Auto-generated method stub
		kSql= "SELECT COUNT(FileCustomerGroup) as count " 
				+ " FROM FileCustomerGroup FileCustomerGroup " 
				+ " WHERE ( FileCustomerGroup.fParent = :fParent ) "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("fParent", fParent);
		
		long singleResult =  (long) query.getSingleResult();
		return (int) singleResult;
	}

	@Override
	public List<FileCustomerGroup> getChilds(String fParent) {
		// TODO Auto-generated method stub
		kSql="SELECT FileCustomerGroup FROM FileCustomerGroup FileCustomerGroup "
				+ " WHERE ( FileCustomerGroup.fParent =:fParent ) "
				+ " ORDER BY FileCustomerGroup.sortNo ASC "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("fParent", fParent);
		
		@SuppressWarnings("unchecked")
		List<FileCustomerGroup> resultList = query.getResultList();
		return resultList;
	}


	@Override
	public List<FileCustomerGroup> getChildren(String fParent) {
		// TODO Auto-generated method stub
		kSql="SELECT FileCustomerGroup FROM FileCustomerGroup FileCustomerGroup "
//				+ " WHERE ( FileCustomerGroup.groupFullID like '%:fParent%' ) "
				+ " WHERE ( FileCustomerGroup.groupFullID like '%" + fParent + "%' ) "
				+ " AND ( FileCustomerGroup.fID <> '" + fParent + "' ) "
				+ " ORDER BY FileCustomerGroup.sortNo DESC"
				;
		Query query = em.createQuery(kSql);
//		query.setParameter("fParent", fParent);
		@SuppressWarnings("unchecked")
		List<FileCustomerGroup> resultList = query.getResultList();
		return resultList;
	}


	
}
